package com.efounder.chat.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.efounder.frame.baseui.BaseFragment;
import com.efounder.chat.R;
import com.efounder.chat.adapter.TelePhoneListAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.Group;
import com.efounder.chat.struct.StructFactory;
import com.efounder.mobilecomps.contacts.User;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author Administrator=lch 会话列表fragment
 */
public class TelephoneRecordFragment extends BaseFragment {
    private final static String TAG = "TelephoneRecordFragment";

    private ListView telePhoneList;
    private TelePhoneListAdapter telePhoneListAdapter;

    private List<ChatListItem> chatListItems = new ArrayList<ChatListItem>();
    private Map<String, ChatListItem> chatListMap;
    private View view;
    private Group group;
    private ListView listView;
    private SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());

    private Handler messageHandler = new MessageHandler(this);

    boolean isFragmentShowing = true;
    private int currentChatUserId = -1;
    public static boolean ISDESTROY = true;

    private Activity activity;

    private static class MessageHandler extends Handler {
        private WeakReference<TelephoneRecordFragment> weakReference;

        public MessageHandler(TelephoneRecordFragment fragment) {
            weakReference = new WeakReference<TelephoneRecordFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    TelephoneRecordFragment fragment = weakReference.get();
                    if (fragment != null) {
                        fragment.telePhoneListAdapter.notifyDataSetChanged();
                    }
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        System.out.println("----onCreateView---");

        view = inflater.inflate(R.layout.telephone_list, container, false);

        listView = (ListView) view.findViewById(R.id.listView);

        chatListMap = new HashMap<String, ChatListItem>();


        listView.setSelector(R.color.transparent);
        telePhoneListAdapter = new TelePhoneListAdapter(activity,
                chatListItems);

        listView.setAdapter(telePhoneListAdapter);
        telePhoneListAdapter.notifyDataSetChanged();

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                User user = WeChatDBManager.getInstance().getOneUserById(chatListItems.get(position).getUserId());
                String mobilePhone = user.getMobilePhone();
                if (mobilePhone.length() == 11) {
                    Intent intent = new Intent(Intent.ACTION_CALL,
                            Uri.parse("tel:" + user.getMobilePhone()));

                    startActivity(intent);
                } else {
//                    Intent intent = new Intent(Intent.ACTION_CALL,
//                            Uri.parse("tel:18363825829"));
                    Toast.makeText(activity, R.string.wechatview_not_get_user_phone, Toast.LENGTH_SHORT)
                            .show();
                }


            }
        });

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("----onResume---");

        chatListItems.clear();

        new Thread(new Runnable() {
            @Override
            public void run() {

                List<ChatListItem> lists = WeChatDBManager.getInstance().getAllChatList();
                Iterator<ChatListItem> iterator = lists.iterator();
                while (iterator.hasNext()) {
                    ChatListItem chatListItem = (ChatListItem) iterator.next();
                    User user = WeChatDBManager.getInstance().getOneUserById(chatListItem.getUserId());

                    if (user.getType() == User.PUBLICFRIEND || chatListItem.getStruct002() ==
                            null || chatListItem.getStruct002().getToUserType() == StructFactory
                            .TO_USER_TYPE_GROUP) {
                        iterator.remove();
                    }

                }
                if(lists.size()>7) {
                    chatListItems.addAll(lists.subList(0, 6));
                }else{
                    chatListItems.addAll(lists.subList(0,lists.size()));
                }


//                for (ChatListItem item : chatListItems) {
//                    // 将查询出的 chatlist列表放入map
//                    String key = String.valueOf(item.getChatType()) + String.valueOf(item
//                            .getUserId());
//                    Log.i(TAG, "onResume输出聊天map的key：" + key);
//                    chatListMap.put(key, item);
//                    if (item.getIsTop() == true)
//                        topIndex++;
//                }
//                //XXX 处理收到的未处理的消息
//                for (IMStruct002 imStruct002 : unHandleReceiveMessage) {
//                    Log.e("--", "-----unHandleReceiveMessage.处理收到的未处理的消息:" + imStruct002);
//                   // chatListMessageListener.handleReceiveMessage(imStruct002);
//                }
//                unHandleReceiveMessage.clear();
//                sortConversationByLastChatTime(chatListItems);
//                sortConversationByIsTop(chatListItems);
                messageHandler.sendEmptyMessage(0);

            }
        }).start();


    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println("----onPause---");
        isFragmentShowing = false;
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("----onStop---");
    }


    @SuppressWarnings("unused")
    private void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }


}
